import Taro from '@tarojs/taro';
import { BIZ_STATUS_CODE, HTTP_STATUS_CODE } from './enum';
import { pageToLogin } from './utils';
// import { pageToLogin } from './utils';

interface Chain {
  requestParams?: unknown;
  proceed: Function;
}

interface Response {
  statusCode: HTTP_STATUS_CODE;
  data: {
    [key: string]: any;
    code: number;
    message: string;
  };
}

/**
 * 自定义拦截器
 */
const customInterceptor = (chain: Chain) => {
  const requestParams = chain.requestParams;

  return chain
    .proceed(requestParams)
    .then((res: Response) => {
      // return res.data;
      if (res.statusCode === HTTP_STATUS_CODE.SUCCESS) {
        // 业务状态码
        const { errCode, errMessage } = res.data;
        // console.log(res, 'ressss')
        if (errCode === null || errCode === undefined) {
          return res.data;
        } else if (
          errCode == BIZ_STATUS_CODE.AUTHENTICATE ||
          Math.abs(errCode) == BIZ_STATUS_CODE.EXPIRED_TOKEN
        ) {
          Taro.setStorageSync('authorize', '');
          Taro.setStorageSync('isLogin', false);
          pageToLogin();

          return Promise.reject('请登录账号');
        } else {
          return Promise.reject(errMessage || '网络异常请重试');
        }
      } else if (res.statusCode === HTTP_STATUS_CODE.AUTHENTICATE) {
        Taro.setStorageSync('authorize', '');
        Taro.setStorageSync('isLogin', false);
        pageToLogin();

        return Promise.reject('请登录账号');
      } else {
        return Promise.reject(res?.data?.errMessage || '网络异常请重试');
      }
    })
    .catch((error: string) => {
      Taro.showToast({
        title: error,
        icon: 'none',
        duration: 1000,
      });
      return Promise.reject(error);
    });
};

const interceptors = [customInterceptor];

export default interceptors;
